﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Beway.ValueAdded.Service;
using Beway.ValueAdded.Model;
using Beway.ValueAdded.Util;
using System.IO;
using System.Xml;
using System.Text;
using System.Net;
using System.Security.Cryptography;
using System.Net.Security;
using Beway.ValueAdded.Model.ViewModel;
using System.Configuration;

namespace Beway.ValueAdded.RechargeGateway.Controllers
{
    public class RechargeController : BaseController
    {
        //
        // GET: /Recharge/
        
        ReUserServ rus = SingletonProvider<ReUserServ>.Instance;
        
      

        public string ORDERID = ""; //订单id       
        public string CURCODE = "01"; //固定参数 01代表人民币
        public string REMARK1 = ""; //备注1
        public string REMARK2 = ""; //备注2 
        public string TXCODE = "MP6000";//由建行统一分配为MP6000
        public string WAPVER = "wap1.2";//默认为1.2
        public string MAGIC = ""; //校验域 ORDERID=20100705140203+PAYMENT=50.00+REMARK1=MIAOSHA+REMARK2=333 字符串md5加密
 

        public ContentResult index()
        {
            log.Error("测试日志写入情况！");

            return Content("test");
        }

        #region 欧飞手机话费/QQ币直接充值接口（不需要支付）
        /// <summary>
        /// 欧飞手机话费/QQ币直接充值接口（不需要支付）
        /// </summary>
        /// <param name="userId">充值平台分配的ID，每个系统都应有唯一的ID</param>
        /// <param name="orderType">1手机，2QQ币</param>
        /// <param name="rechargeTarget">手机号/QQ号</param>      
        /// <param name="rechargeAmount">充值数量/金额</param>
        /// <param name="orderNo">调用系统中的订单号（需要唯一）</param>
        /// <param name="mac">校验字符串，通过md5(userId|orderType|rechargeTarget|rechargeAmount|orderNo|verifymac)获得</param>
        /// <returns>-4账户禁用  -5ip不在白名单 ，-6不在有效期，-7额度不足 -3充值平台异常，-2mac校验失效，-1用户不存在，0订单号已存在，请更换，1成功，2充值中，3充值失败，可以退款</returns>       
        public ActionResult OrderNoPay(int orderType, string rechargeTarget, int rechargeAmount, string orderNo, string mac,int userId=0)
        {
            int ret = -10;
            ReUser user = rus.GetByUserId(userId);
          
            bool isvalidate = UserValidate(Request, rechargeAmount,user, out ret);//客户身份验证
            if (isvalidate)
            {
                string verifyStr = string.Format("{0}|{1}|{2}|{3}|{4}|{5}", userId, orderType, rechargeTarget, rechargeAmount, orderNo, user.VerifyMac);
                verifyStr = beway.common.Encryption.Md5Encry32bit(verifyStr);
                if (verifyStr == mac.ToLower()) //验证通过
                {                  
                    string orderID = "RE" + beway.common.FileUtil.GetFileNameFromSystemAuto() + userId.ToString();
                    Recharge rm = new Recharge()
                    {
                        UserID = userId,
                        OrderAmount = rechargeAmount,
                        UserOrderNo = orderNo,//调用系统提供的订单号
                        OrderID = orderID,
                        OrderTime = System.DateTime.Now,
                        PayStatus = 0,
                        RCTarget = rechargeTarget,
                        RCType = orderType,
                        RechargeErrorReason = "",
                        RechargeStatus = 0,
                        RechargeAmount = rechargeAmount
                    };
                    int rcid = rs.AddForUniqueOrderNo(rm);
                    if (rcid > 0)
                    {
                        //更新项目的额度（有可能与实际的总额度有出入，为考虑性能，未做精准控制）
                        user.RechStock -= rechargeAmount;
                        rus.UpdateStock(user);

                        //调用充值接口
                        string reRet = rs.RechargeTrade(rm,user); //0充值中,  1成功, 9充值失败，可以退款, 11运营商维护，暂不能充值
                        if (reRet == "")//系统异常
                        {
                            ret = -3;//充值平台异常,返回retcode为空
                        }
                        else
                        {
                            //ret 1成功,2充值中,3失败
                            if (reRet == "0") //充值中
                            {
                                ret = 2;
                            }
                            else if (reRet == "1")//成功
                            {
                                ret = 1;
                            }
                            else if (reRet == "9")//充值失败，可以退款
                            {
                                ret = 3;
                            }
                            else if (reRet == "11")//运营商维护，暂不能充值
                            {
                                ret = 3;
                            }
                            else
                            {
                                ret = 3;
                            }
                        }
                        //更新充值结果
                        rs.Update(rm);                       
                    }
                    else
                    {
                        ret = 0;//订单号已存在，请更换
                    }
                }
                else
                {
                    ret = -2;//mac检验失败
                }
            }            

            return Content(ret.ToString());
        }
        
        #endregion
         
        #region 接收欧飞充值结果通知方法
        /// <summary>
        /// 充值结果接收action，可处理手机话费、QQ币及流量包通知
        /// 系统请求参数：ret_code 充值后状态，1代表成功，9代表撤消
        ///sporder_id  SP订单号
        ///ordersuccesstime 处理时间
        ///err_msg 失败原因
        ///提交方式为：POST
        ///如：http://www.xxxx.com/retonline.jsp?ret_code=1&sporder_id=1100
        ///注：SP得到请求信息后，请自行处理系统订单状态。如SP系统问题没收到返回结果，或者在长时间内没有收到充值成功信息，可再次发送此笔订单到查询接口查看充值状态（SP订单号为原订单号），如还是没有充值成功请和CP客服联系，以做进一步处理。
        /// </summary>
        /// <returns></returns>
        public ActionResult RecResult(string ret_code, string sporder_id, string ordersuccesstime, string err_msg)
        {
            string strRet = "";
            int isok = rs.RechargeResultReceive(sporder_id, int.Parse(ret_code), err_msg);
            if (isok == 0)//已经收到过通知
            {
                strRet = "已收到充值结果，不需要再次处理！";
            }
            else if (isok == 1)
            {
                strRet = "处理成功！";
            }
            else if (isok == -0)
            {
                strRet = "没找到订单，或订单不唯一！";
            }
            ViewBag.ret = strRet;

            log.Info("充值结果异步通知：" + strRet + ",返回数据：" + ret_code + "," + sporder_id + "," + ordersuccesstime + "," + err_msg);

            return View();
        }
        #endregion

        #region 查询手机号是否可进行充值方法（欧飞接口）
        /*
          http://api2.ofpay.com/telcheck.do?phoneno=13813856456&price=50&userid=Axxxxx
            price为充值面值。
            注：price值可为空，为空时接口默认为面值50元
            返回：1#成功#0000&江苏南京
            1表示能充值，其它表示不能充。
         */
        /// <summary>
        /// 检查手机号是否可以进行充值
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <param name="amount">充值金额</param>
        /// <returns>1可以充值，0不可充值</returns>
        public ContentResult MobileNoRechargeCheck(string mobile, int amount)
        {
            string retStr = "0";
            string url = "http://api2.ofpay.com/telcheck.do";
            string param = string.Format("phoneno={0}&price={1}&userid={2}", mobile, amount, Config.ofUserID);
            string ret = "";
            ret = Util.HttpHelper.HttpGet(url, param);
            try
            {
                ret = Util.HttpHelper.HttpGet(url, param);

                if (ret.Split('#')[0] == "1")
                {
                    retStr = "1";
                }
            }
            catch (Exception ex)
            {
                log.Error("查询手机号是否可充值异常：" + ex.ToString());
            }
            return Content(retStr);
        }
        #endregion

        #region 欧飞接口查询手机号充值结果
        /// <summary>
        /// 欧飞接口查询手机号充值结果
        /// </summary>
        /// <param name="userId">充值平台为子网站分配的userId</param>
        /// <param name="orderNo">充值时的订单号</param>
        /// <returns>返回形式如：1#充值成功 或0#充值中 9#充值失败 -1#未查询到订单</returns>
        public ContentResult MobileRechargeResult(int userId, string orderNo)
        {
            int retCode = -1;
            string retStr = "未找到订单记录";
            Recharge model = rs.GetByUserIdAndOrderNo(userId, orderNo);
            if (model != null && model.RCID > 0)
            {
                if (model.RechargeStatus == 0)
                {
                    if (model.RechargeErrorReason != "")//已经返回过充值结果，不需要再次查询
                    {
                        retStr = model.RechargeErrorReason;
                    }
                    else//调用欧飞查询接口
                    {
                        /*
                         地址：http://202.102.53.141:83/api/query.do?userid=xxxxx&spbillid=spxxxxxx
                         返回（1，0，9，-1），其中一项。 1充值成功，0充值中，9充值失败，-1找不到此订单。
                         如果返回-1，请您务必进入平台或者联系欧飞客服进行核实，避免给自己带来不必要的损失。
                         */
                        string checkUrl = "http://202.102.53.141:83/api/query.do";
                        string param = string.Format("userid={0}&spbillid={1}", Config.ofUserID, model.OrderID);
                        string ret = "";
                        try
                        {
                            ret = Util.HttpHelper.HttpGet(checkUrl, param).Trim();
                        }
                        catch (Exception ex)
                        {
                            log.Error("欧飞接口查询充值结果异常:" + ex.ToString());
                        }
                        if (ret == "1")//充值成功
                        {
                            model.RechargeStatus = retCode = 1;
                            model.RechargeErrorReason = "";
                            retStr = "充值成功";
                        }
                        else if (ret == "0")
                        {
                            model.RechargeStatus = retCode = 0;
                            model.RechargeErrorReason = "";//充值中，不记录，子系统可以再次查询
                            retStr = "充值中";
                        }
                        else if (ret == "9")
                        {
                            model.RechargeStatus = retCode = 9;
                            model.RechargeErrorReason = "充值失败（查询获到状态）";
                            retStr = "充值失败";
                        }
                        else if (ret == "-1")
                        {
                            model.RechargeStatus = retCode = -1;
                            model.RechargeErrorReason = "欧未找到订单，需要核实";
                            retStr = "未查询到订单";
                        }
                        else
                        {
                            model.RechargeStatus = 0;
                            model.RechargeErrorReason = "未知 ret=" + ret;
                            retStr = "未知";
                        }
                        //更新到数据库
                        rs.RechargeStatusUpdate(model.RCID, model.RechargeStatus.Value, model.RechargeErrorReason);
                    }
                }
                else
                {
                    retCode = 1;
                    retStr = "充值成功";
                }
            }
            return Content(retCode + "#" + retStr);
        }
        #endregion

        #region 根据用户ID，返回此用户所有订单
        /// <summary>
        /// 根据用户ID，返回此用户所有订单
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public JsonResult OrderList(int userId)
        {
            List<Recharge> list = rs.OrderList(userId);
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        #endregion

       
 

        #region 查询流量包充值结果
        public ActionResult QueryResult()
        {

            return View();
        }
        /// <summary>
        /// 查询充值流量包充值结果
        /// </summary>
        /// <param name="userId">商户Id</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="orderType">订单类型</param>
        /// <returns></returns>
        public ContentResult QueryFlowResult(int userId, string orderNo, int rcType)
        {
            int ret = -1;
            string record = "未查到充值记录";
            Recharge rcModel = rs.GetByUIdAndOrderNoAndRcType(userId, orderNo, rcType);
            if (rcModel != null && rcModel.RCID > 0)
            {
                if (rcModel.RechargeStatus == 2)
                {
                    ret = 0;
                    record = "充值中";
                }
                else if (rcModel.RechargeStatus == 1)
                {
                    ret = 1;
                    record = "充值成功";
                }
                else if (rcModel.RechargeStatus == 3)
                {
                    ret = 9;
                    record = "  ，" + rcModel.RechargeErrorReason;
                }
            }
            return Content(ret + "#" + record);
        }
        #endregion

        #region 欧飞流量充值接口,次月生效，当月有效，全国
        /// <summary>
        /// 欧飞充值手机上网流量包(次月生效，当月有效，全国)目前三家运营商共有用面值只有10元，30元，
        /// 其中移动10元对应70M流量，联通电信10元对应100M流量
        /// 30元均对应500M流量
        /// </summary>
        /// <param name="userId">账户Id</param>
        /// <param name="rechargeTarget">充流量手机号</param>
        /// <param name="rechargeAmount">充值面值，需要查询欧飞文档，每家公司面值和流量值并不相同</param>
        ///<param name="flowAmount">流量值，需要在后面带“M”或“G”如：30M, 1G</param>
        /// <param name="orderNo">订单号</param>
        /// <param name="mac">校验</param>
        /// <returns></returns>
        public ActionResult OfFlowOrder(int userId, string rechargeTarget, int rechargeAmount, string flowAmount,string orderNo, string mac)
        {
            int ret = -10;
            ReUser user = rus.GetByUserId(userId);
            if (user != null && user.UserID > 0)
            {
                if (user.RechStatus > 0) //此用户是否还可以充值
                {
                    string verifyStr = string.Format("{0}|{1}|{2}|{3}|{4}|{5}", userId, rechargeTarget, rechargeAmount, flowAmount, orderNo, user.VerifyMac);
                    verifyStr = beway.common.Encryption.Md5Encry32bit(verifyStr);
                    if (verifyStr == mac.ToLower()) //验证通过
                    {
                        string orderID = "RE" + beway.common.FileUtil.GetFileNameFromSystemAuto() + userId.ToString();
                        Recharge rm = new Recharge()
                        {
                            UserID = userId,
                            OrderAmount = rechargeAmount,
                            UserOrderNo = orderNo,//调用系统提供的订单号
                            OrderID = orderID,
                            OrderTime = System.DateTime.Now,
                            PayStatus = 0,
                            RCTarget = rechargeTarget,
                            RCType = 4, //流量包
                            RechargeErrorReason = flowAmount,
                            RechargeStatus = 0,
                            RechargeAmount = rechargeAmount,
                        };
                        int rcid = rs.AddForUniqueOrderNo(rm);
                        if (rcid > 0)
                        {
                            //调用充值接口
                            bool reRet = rs.OfFlowOrderTrade(rm);
                            if (reRet == true)
                            {
                                ret = 1;//充值中
                            }
                            else
                            {
                                ret = 9;
                            }
                            //更新充值结果
                            rs.Update(rm);
                        }
                        else
                        {
                            ret = 0;//订单号已存在，请更换
                        }
                    }
                    else
                    {
                        ret = -2;//mac检验失败
                    }
                }
                else
                {
                    ret = -4;//此用户充值功能被关闭
                }
            }
            else
            {
                ret = -1;//用户不存在
            }
            return Content(ret.ToString());
        }


        //充值流量包接收通知接口与话费和Q币接收通知接口一致，见：RecResult
        #endregion
         

    }
}
